package com.sunday.player;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.sunday.player.adapter.adapter_playlist;
import com.sunday.player.domain.musicData;
import com.sunday.player.interfaceutil.interface_AdapterCallback;
import com.sunday.player.service.PlayerService;
import com.sunday.player.util.playerControl;
/**
 * 
- 리스트 편집 
   + 기본기능
   1. 추가 
   2. 삭제(전체 / 일부) 
   3. 이름변경
   4. 순서변경(전체/ 일부)
  
   
   
- 곡목록편집
   + 메뉴기능
   1. 추가 
   2. 삭제 (전체 / 일부)(리스트에서만 / 파일까지)
   3. 정렬 (기본 가나다)(곡/앨범/아티스트)
   4. 다른리스트로 이동 / 복사
   + 클릭기능
   1. TAG 변경 (클릭시)(인코딩 변경 지원)
   2. 미리듣기(재생아님) 
   3.  
 * 
 * 참고하기 : https://android.googlesource.com/platform/packages/apps/Music.git/+/donut-release
 * 
 * @author user
 *
 */
public class Activity_Player extends basicActivity implements OnClickListener{
    
    private ImageView IB_play_pause;
    private SeekBar PB_timebar;
    private final Handler mHandler = new Handler() ;
    private ListView ListView;
    private adapter_playlist adapter_playlist;
    private boolean isPlaying = false;
    private Timer MusicTimer ;
    private boolean mPressed = false;;
    private TextView TV_proTime;
    private TextView TV_Time;
    
    private interface_AdapterCallback adapterCallback = new interface_AdapterCallback() {
        
        @Override
        public void onItemClickCallback(int Position, int State, int Action) {
            	playerControl.Trace_i("Position = "+Position+"	State="+State+"	Action= "+Action, TAG);
    		switch (Action) {
		case interface_AdapterCallback.Play:
		    try {
			musicData MD = PlayerControler.getTrackDatatoIndex(Position);
			if(MD == null){
			    if(MD.get_data() != null ){
				
			    }
			    
			}
			PlayerControler.SelectPlay(0, Position);
		    } catch (Exception e) {
			e.printStackTrace();
		    }
		    break;

		default:
		    break;
		}
    	
        }
    };
    	OnSeekBarChangeListener change_listener = new OnSeekBarChangeListener() {
        	@Override
        	public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
        		
        	}
        	@Override
        	public void onStartTrackingTouch(SeekBar seekBar) {
        		mPressed = true;
        	}
        	@Override
        	public void onStopTrackingTouch(SeekBar seekBar) {
        		mPressed = false;
        		try {
        		    PlayerControler.setPlayerPosition(PB_timebar.getProgress());
        		} catch (RemoteException e) {
        		    e.printStackTrace();
        		}
        				
        		
        	}
    	};
	OnSeekBarChangeListener Volume_listener = new OnSeekBarChangeListener() {
        	@Override
        	public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
        		
        	}
        	@Override
        	public void onStartTrackingTouch(SeekBar seekBar) {
        		mPressed = true;
        	}
        	@Override
        	public void onStopTrackingTouch(SeekBar seekBar) {
        		mPressed = false;
        		try {
        		    PlayerControler.setPlayerPosition(PB_timebar.getProgress());
        		} catch (RemoteException e) {
        		    e.printStackTrace();
        		}
        				
        		
        	}
	};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	setContentView(R.layout.activity_player);
        super.onCreate(savedInstanceState);
        
        IB_play_pause = (ImageView)findViewById(R.id.btn_play);
        PB_timebar = (SeekBar)findViewById(R.id.progress_bar);
        PB_timebar.setOnSeekBarChangeListener(change_listener);
        ListView = (ListView)findViewById(R.id.listView_play);
        TV_proTime = (TextView)findViewById(R.id.progress);
        TV_Time = (TextView)findViewById(R.id.duration);
        findViewById(R.id.btn_play).setOnClickListener(this);
        findViewById(R.id.btn_next).setOnClickListener(this);
        findViewById(R.id.btn_prev).setOnClickListener(this);
   }
   
    
    
    
    @Override
    protected void onStart() {
	
	 
        super.onStart();
        
    }
    @Override
    public void onServiceConnected() {
        super.onServiceConnected();
        
        try {
	   
	    
	   
		if(PlayerControler.getMusicList().size() == 0){
		    // 재생목록이 없다면 호출
		   Playlist_allget();
		  
		    if(PlayerControler.getMusicList().size() == 0){
			
			/**
			 * 불러올 재생목록이 없다면 자동으로 뮤직 리스트 화면으로 
			 */
			 startActivity(new Intent(this, Activity_listEditer.class));
			
			
			/**
		         * 최초구동시 mp3 구성으로 이동
		         */
			/*
			if(sundaySharedPreferences.getFirstMp3listLoad()){
		            startActivity(new Intent(this, Activity_listEditer.class));
		        }
		        */
		    }
		        
		}
		isPlay(PlayerControler.isPlaying());
	    
	    
	    
	    if(PlayerControler.getMusicList().size() != 0){
		adapter_playlist  = new adapter_playlist(this, 0, PlayerControler.getMusicList(),adapterCallback);
		ListView.setAdapter(adapter_playlist);
		
	    }
	} catch (RemoteException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
        
        
        
    };
    
    @Override
    protected void onResume() {
        super.onResume();
        try {
	    if(PlayerControler != null && PlayerControler.isPlaying()){
	        isPlay(true);
	    }else{
		isPlay(false);
	    }
	} catch (RemoteException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
        
    }
    @Override
    protected void onPause() {
        super.onPause();
    
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_player, menu);
        
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	case R.id.menu_settings:
	    startActivity(new Intent(this, Activity_listEditer.class));
	    break;

	default:
	    break;
	}
	return false;
	//return super.onOptionsItemSelected(item);
    }
    

    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.btn_play:
	    try {
		if(PlayerControler.isPlaying()){
			isPlay(false);
			PlayerControler.Control_pause();
		    
		}else{
			isPlay(PlayerControler.Control_play());
		    
		}
	    } catch (RemoteException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	    break;
	case R.id.btn_next:
	    try {
		PlayerControler.Control_next();
	    } catch (RemoteException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	    break;
	    
	case R.id.btn_prev:
	    try {
		PlayerControler.Control_prev();
	    } catch (RemoteException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	    break;

	default:
	    break;
	}
    }
    
    /**
     * t 라면 정지표시 f 라면 플레이 버튼
     * @param isplay
     */
    public void  isPlay(boolean isplay){
	isPlaying = isplay;
	if(isplay){
	    IB_play_pause.setImageResource(R.drawable.btn_pause);
	    if(MusicTimer == null) {
		MusicTimer = new Timer();
	    }
		MusicTimer.schedule(new MusicTimer(), 0, 1000);
		try {
		    onMusicDataSet(PlayerControler.getTrackData());
		} catch (RemoteException e) {
		    e.printStackTrace();
		}
	}else{
	    IB_play_pause.setImageResource(R.drawable.btn_play);
	    
	}
	   
	
    }
    
    
    private class MusicTimer extends TimerTask {
	Runnable time = new Runnable() {
	    
	   

	    @Override
	    public void run() {
		
		    try {
			if(PlayerControler == null){
			    return;
			}
			if(mPressed == true){
			    return ;
			}
			
			int pos = PlayerControler.getPosition();
			int progress = pos/1000;
			if(progress > 0) {
			    	int percent = progress;//*100;// / mDuration;
				PB_timebar.setProgress(percent);
				int min = progress/60;
				int sec = progress%60;
				TV_proTime.setText(String.format("%02d:%02d", min, sec));
				
			}
			
			
			
			
			
		   
		    } catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }
		    
		
	    }
	};
	@Override
	public void run() {
	    mHandler.post(time);
	    
	} 
    }
    @Override
    protected void recivePlayerState(int state) {
	switch (state) {
	case PlayerService.PLAYER_PLAY:
	    isPlay(true);
	   
	    
	    
	    break;
	case PlayerService.PLAYER_STOP:
	    isPlay(false);
	    break;

	}
    
    }
    /**
     * 화면이나 음악 변경시 표시 내용변경
     * @param MD
     */
    public void onMusicDataSet(musicData MD){
	if(MD == null){
	    return ;
	}
	
	int du = (Integer.valueOf(MD.getDuration()))/1000;
	PB_timebar.setMax(du);
	PB_timebar.setProgress(0);
	int min =  du/60 ;
	int sec =  du %60;
	TV_Time.setText(String.format("%02d:%02d",min, sec));
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
    }
}
